package com.zemo.base.api.controller;

import com.zemo.base.common.util.DateUtils;
import com.zemo.base.common.util.JsoupUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * @author Zemo
 * @date 2011-11-23 下午03:20:23
 * @description:
 */
public abstract class BaseController {
    private static final Log log = LogFactory.getLog(BaseController.class);
    public static final String PAGE_SIZE = "20";
    public static final String PAGE_NO = "1";

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        //防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {

                setValue(text == null ? null : JsoupUtil.clean(text));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : null;
            }
        });

        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    @ModelAttribute
    public void init(HttpServletRequest request, Model model) {

        // 系统全局信息


    }

    /**
     * 返回站点地址
     *
     * @param request
     * @return
     */
    public String getBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    public String getResource(String key) {
        try {
            return ResourceBundle.getBundle("error_info").getString(key);
        } catch (Exception e) {
            return "Can't find resource for bundle";
        }
    }


    public Long getCurrentUserId(HttpServletRequest request) {
        /*ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (user != null && user.id != null) {
            return user.id;
        } else {
            return null;
        }
*/
        return null;
    }

    /**
     * 页面对象转化为字符串
     *
     * @param request
     * @param key
     * @return
     */
    public String fmtToString(HttpServletRequest request, String key) {
        log.debug("request will format to string: " + request.getParameter(key));

        Object str = request.getParameter(key);
        if (str == null || str == "") {
            return null;
        } else {
            return HtmlFliter(str.toString().trim());
        }
    }

    /**
     * Object对象转化为字符串
     *
     * @return
     */
    public String fmtToString(Object object) {
        log.debug("object will format to string: " + object);

        if (object == null || object == "") {
            return null;
        } else {
            return HtmlFliter(object.toString().trim());
        }
    }





    /**
     * Object对象转化为整数对象
     *
     * @return
     */
    public int fmtToInt(Object object) {
        log.debug("request will format to int: " + object);

        if (object == null || object == "") {
            return 0;
        } else {
            try {
                return Integer.parseInt(object.toString().trim());
            } catch (NumberFormatException e) {
                log.error(e.getStackTrace());
                return 0;
            }
        }
    }


    /**
     * 判断用户与系统登陆用户是否同一个用户
     *
     * @return
     */
    public Boolean havePermissionUser(Long userId) {
        /*log.debug("havePermissionUser begin: userid=" + userId);

        UserEntity user = userService.getUser(userId);

        // 管理员权限
//		for (UserRole userRole : user.getUserRoles()) {
//			if (userRole.getRole().getCode().equals("ROLE_ADMINISTRATOR") || userRole.getRole().getCode().equals("ROLE_SUPERVISOR")) {
//				return true;
//			};
//		}

        // 如果用户和登陆用户是一个用户，则有权限
        if (userId.equals(getCurrentUserId(null))) {
            return true;
        } else {
            return false;
        }
*/
        return false;
    }

    /**
     * 判断用户是否有管理员权限
     *
     * @return
     */
    public Boolean havePermissionAdmin(Long userId) {
        log.debug("havePermissionAdmin begin: userid=" + userId);

//        User user = userService.getUser(userId);

        // 管理员权限
//		for (UserRole userRole : user.getUserRoles()) {
//			if (userRole.getRole().getCode().equals("ROLE_ADMINISTRATOR") || userRole.getRole().getCode().equals("ROLE_SUPERVISOR")) {
//				return true;
//			};
//		}

        return false;

    }

    // 避免xss跨站脚本
    public String HtmlFliter(String in){

        in = in.replaceAll("&", "&amp;");
        in = in.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        in = in.replaceAll("\r", "");
        in = in.replaceAll("\n", "<br>");
        in = in.replaceAll("\"", "&quot;");
        in = in.replaceAll(" ", "&nbsp;");
        in = in.replaceAll("'", "&acute;");
        in = in.replaceAll("eval\\((.*)\\)", "");
        in = in.replaceAll("[\\\"\\\'][\\s]*((?i)javascript):(.*)[\\\"\\\']", "\"\"");
        //in = in.replaceAll("((?i)script)", "");

        return in;
    }
}
